<?php

if(!defined('OI')) {
			
	print '<h1>Access Error</h1>Sorry, this file can not be accessed directly, this is strictly forbidden!';
	exit();
				
}

class Resources {

	# Store digitalUniversity
	private $digitalUniversity = NULL;

	/*
	 * Constructor: Store instance of sitebuilder
	 * 	- PHP5 now uses pass by reference so we do not need to store the reference
	*/
	public function __construct(DigitalUniversity &$digitalUniversity) {
	
		$this->digitalUniversity =& $digitalUniversity;
				
	}
	
	/*
	 * Destructor: Clean memory parts
	*/
	public function __destruct() {
		
		unset($this->digitalUniversity);
		
	}
	
	/*
	 * getResources: Query the latest resources
	 *
	 * @return array - A list of resources
	*/
	private function getResources() {
		
		# Define variables
		$whereString = '';
		
		# Search filter
		if(!empty($this->digitalUniversity->input['act']) && ($this->digitalUniversity->input['act'] == 'search') && !empty($this->digitalUniversity->post['keyword'])) {
			
			$whereString = " AND r.title LIKE '%{$this->digitalUniversity->post['keyword']}%'";
			
		}
		
		# Particular module
		$resources = $this->digitalUniversity->db->getResults("SELECT r.*, u.firstName, u.surname, u.username FROM resources r
		LEFT JOIN users_resources ur ON (ur.resourceID = r.resourceID)
		LEFT JOIN users u ON (u.userID = ur.userID)
		WHERE r.isApproved = '1'
		{$whereString}
		LIMIT 20");
		
		return $resources;
		
	}
	
	/*
	 * getResource: Query the database for the current resource.
	 *
	 * @return array - Details of the resource
	*/
	private function getResource() {
		
		# Particular module
		$resource = $this->digitalUniversity->db->getRow("SELECT r.*, u.firstName, u.surname, u.username FROM resources r
		LEFT JOIN users_resources ur ON (ur.resourceID = r.resourceID)
		LEFT JOIN users u ON (u.userID = ur.userID)
		WHERE r.resourceID = '{$this->digitalUniversity->input['resource']}' AND r.isApproved = '1'
		LIMIT 1");
		
		return $resource;
		
	}
	
	/*
	 * getComments: Get all comments for a given resource.
	 *
	 * @return array - Resource comments
	*/
	private function getComments() {
	
		# Particular module
		$comments = $this->digitalUniversity->db->getResults("SELECT c.*, u.firstName, u.surname, u.username FROM resources_comments rc
		LEFT JOIN comments c ON (c.commentID = rc.commentID)
		LEFT JOIN users u ON (u.userID = c.userID)
		WHERE rc.resourceID = '{$this->digitalUniversity->input['resource']}' AND c.status = '1'
		ORDER BY time DESC
		LIMIT 20");
		
		return $comments;			
		
	}
	
	/*
	 * getRatings: Get all ratings for a given resource.
	 *
	 * @return array - Resource ratings
	*/
	private function getRatings() {
	
		# Particular module
		$ratings = $this->digitalUniversity->db->getRow("SELECT COUNT(*) as totalVotes, SUM(rating) as sumVotes, (
			SELECT userID FROM resources_ratings
			WHERE resourceID = '{$this->digitalUniversity->input['resource']}' AND userID = '{$this->digitalUniversity->user['userID']}'
		) AS userHasVoted FROM resources_ratings 
		WHERE resourceID = '{$this->digitalUniversity->input['resource']}'");
				
		return $ratings;			
		
	}
	
	private function showRatings(&$resourceID) {
		
		# Get ratings
		$ratings = $this->getRatings();
		
		# Define variables
		$rating = 0;
		$width = 0;
		$userHasVoted = false;
		$class = '';
		
		# Any ratings?
		if(!empty($ratings)) {
			
			# Average rating
			$average = ($ratings['totalVotes'] != 0 ? $ratings['sumVotes'] / $ratings['totalVotes'] : 0);
			
			
			# Width of stars
			if($average != 0) {
				$width = (($average * 2) * 10 + ((ceil($average) - 1) * 10));
			}
			
			# Has the user voted?
			if($ratings['userHasVoted'] == $this->digitalUniversity->user['userID']) {
				$userHasVoted = true;	
			}
			
		}
		
		if($userHasVoted) {
			$class = ' inactive';
		}
		
		echo '<h4>Rating</h4>
		<section class="contentBlock clearfix ratingBlock"  id="ratingSubmit" data-resource="'.$resourceID.'" data-type="resource"'.($userHasVoted ? ' data-disabled="true"' : '').'>
			<div class="rating">
				<div class="darkStar" style="width: '.$width.'px;">&nbsp;</div>
				<div class="lightStar star_1'.$class.'" data-rating="1">&nbsp;</div>
				<div class="lightStar star_2'.$class.'" data-rating="2">&nbsp;</div>
				<div class="lightStar star_3'.$class.'" data-rating="3">&nbsp;</div>
				<div class="lightStar star_4'.$class.'" data-rating="4">&nbsp;</div>
				<div class="lightStar star_5'.$class.'" data-rating="5">&nbsp;</div>
				<div class="percentage">'.$average.'</div>
			</div>';
			if($average != 0) {
				echo '<h3 class="votesCast">'.$ratings['totalVotes'].' vote'.(($ratings['totalVotes'] != 1) ? 's' : '').' cast</h3>';	
			}
			if(!$userHasVoted) {
				echo '
				<div class="voteButtonContainer">
					<div class="ratingButton" data-rating="1">1</div>
					<div class="ratingButton" data-rating="2">2</div>
					<div class="ratingButton" data-rating="3">3</div>
					<div class="ratingButton" data-rating="4">4</div>
					<div class="ratingButton ratingButtonLast" data-rating="5">5</div>
				</div>';
			}
		echo '</section>';
			
	}
	
	private function showResource() {
		
		# Get current module
		$resource = $this->getResource();
		
		# Report resource
		if(!empty($resource) && !empty($this->digitalUniversity->input['act'])) {
			
			# Process report
			if($this->digitalUniversity->input['act'] == 'report') {
			
				$this->digitalUniversity->db->query("UPDATE resources SET isApproved = '0' WHERE resourceID = '{$resource['resourceID']}' LIMIT 1");				
				return $this->digitalUniversity->redirect('resources&act=reported');
			
			}
			
		}
						
		echo '
		<section class="leftColumn">
			<h1>'.(!empty($resource['title']) ? $resource['title'] : 'Resource').'</h1>
			<nav class="pageTab">
				<a class="focus" href="#" data-tab="resources">Details</a>
			</nav>';
			
			# No resource
			if(empty($resource)) {
				
				echo '<p>This resource does not exist.</p>';
			
			} else {
					
				# Page title
				$this->digitalUniversity->addPageTree($resource['title'], $this->digitalUniversity->config['scripturl'].'page=resources&resource='.$resource['resourceID']);
								
				# Resource details				
				echo '<section class="contentBlock clearfix">
					<article class="document '.$resource['type'].'">
						<h5 class="title">'.$resource['title'].'</h5>
					</article>
					<article class="resourceDetails">
						<table>
							<tr>
								<td>Title:</td>
								<td>'.$resource['title'].'</td>
							</tr>
							<tr>
								<td>Type:</td>
								<td>'.(($resource['type'] == 'pdf') ? strtoupper($resource['type']) : ucfirst($resource['type'])).'</td>
							</tr>
							<tr>
								<td>Added by:</td>
								<td>'.$resource['firstName'].' '.$resource['surname'].'</td>
							</tr>
							<tr>
								<td>Added on:</td>
								<td>'.$this->digitalUniversity->dateTimer('time', $resource['time']).'</td>
							</tr>
						</table>
					</article>
				</section>';
				
				# Get comments
				$comments = $this->getComments();
				
				# Can administrate
				if($this->digitalUniversity->user['groupLevel'] == 4) {
					$canAdmin = true;	
				} else {
					$canAdmin = false;
				}
				
				# Resource comments
				echo '<h4>Comments</h4>
				<section class="contentBlock clearfix">
					<section class="commentsContainer" id="commentsContainer">';
					
					# Do we have any comments?
					if(!empty($comments)) {
						
						foreach($comments as $k => $v) {
						
							echo '<article>
								<h5>
									<aside>'.$this->digitalUniversity->timeSince($v['time']).($canAdmin ? '<br /><br /><a href="#">delete</a>' : '').'</aside>
									'.$v['firstName'].' '.$v['surname'].'
								</h5>
								<p>'.html_entity_decode($v['comment'], ENT_QUOTES, 'UTF-8').'</p>
							</article>';
							
						}
						
					} else {
					
						echo '<article id="noComments">
							<p>This resource has no comments.</p>
						</article>';
						
					}
					
				echo '<textarea name="commentEntryInput" title="Enter a comment.." placeholder="Enter a comment.." data-type="resource" data-resource="'.$resource['resourceID'].'"></textarea>
					<p class="tip"><strong>Tip:</strong> Use the enter key to save your comment. CTRL + Enter produces a new line.</p>
					</section>
				</section>';
				
			}
			
		echo '</section>
		
		<section class="rightColumn">';		
				
			# Display ratings
			if(!empty($resource)) {
				
				$this->showRatings($resource['resourceID']);
							
				$saveLink = $this->digitalUniversity->config['root_url'].'uploads/'.$resource['location'];
			
				echo '<h4>Actions</h4>
				<section class="contentBlock clearfix">
					<a class="save" href="'.$saveLink.'" target="_blank">Save</a>
					<a class="open" href="'.$saveLink.'">Open</a>
					<a class="report" href="'.$this->digitalUniversity->config['scripturl'].'page=resources&resource='.$resource['resourceID'].'&act=report" style="left: 135px;">Report</a>
				</section>';
				
			}
				
		echo '</section>';
		
	}
	
	/*
	 * loadPage: Detect the current page being viewed and output the relevant
	 * page contents
	*/
	public function outputPage() {
		
		# Page title
		$this->digitalUniversity->addPageTree('Resources', $this->digitalUniversity->config['scripturl'].'page=resources');
		
		# View single resource
		if(isset($this->digitalUniversity->input['resource'])) {
			
			return $this->showResource();
			
		}
		
		# Search page
		if(!empty($this->digitalUniversity->input['act']) && ($this->digitalUniversity->input['act'] == 'search') && !empty($this->digitalUniversity->post['keyword'])) {				
			$isSearch = true;				
		} else {
			$isSearch = false;
		}
			
		# Get resources
		$resources = $this->getResources();
			
		echo '<section class="fullPageWidth">
			<h1>Resources</h1>
			<nav class="pageTab">
				<a class="focus" href="#" data-tab="latest">Latest</a>				
				<a href="#" data-tab="search">Search</a>
				<a class="right" href="'.$this->digitalUniversity->config['scripturl'].'page=modules" data-tab="notabber">Modules</a>
				<a class="right" href="'.$this->digitalUniversity->config['scripturl'].'page=book" data-tab="notabber">Books</a>
			</nav>';
			
			if(!empty($this->digitalUniversity->input['act'])) {
				
				if($this->digitalUniversity->input['act'] == 'reported') {
				
					echo '<p class="noticeBox"><strong>Reported:</strong> This resource has been reported and will be reviewed as soon as possible.</p>';
						
				}
					
			}
			
			echo '<!-- Open: tab_search -->
			<section id="tab_search" class="dataTab'.(!$isSearch ? ' hidden' : '').'">
				<section class="contentBlock clearfix addNewResource">
					<form action="'.$this->digitalUniversity->config['scripturl'].'page=resources&act=search" method="post">
					<p class="noUpper">
						<label for="keyword">Keyword:</label> <input type="text" value="'.(!empty($this->digitalUniversity->post['keyword']) ? $this->digitalUniversity->post['keyword'] : '').'" id="keyword" name="keyword" />
					</p>
					<input type="submit" class="submitButton" name="searchResources" value="Search" />
				</form>				
				</section>
			</section>
			<!-- Close: tab_search -->
			
			<section id="tab_latest" class="dataTab">';
						
			# Search page
			if($isSearch && empty($resources)) {								
				echo '<p class="noticeBox"><strong>Search:</strong> Your search returned no results.</p>';				
			}
			
			# Are we lending anything?
			if(!empty($resources)) {
				
				echo '<section class="contentBlock clearfix">
				<h2>Latest Resources</h2>';
					
				foreach($resources as $k => $v) {
												
					if(($k+1) % 7 == 0) {
						$class = ' lastChild';
					} else {
						$class = '';
					}
						
					echo '
					<a href="'.$this->digitalUniversity->config['scripturl'].'page=resources&resource='.$v['resourceID'].'">
						<article class="document '.$v['type'].$class.'">
							<h5 class="title">'.$v['title'].'</h5>
						</article>
					</a>';
							
				}
														 
				echo '</section>';
				
			}
			
			echo '</section>
		</section>';
										
	}
		
}

?>